<?php

class Phpfox_File_Link {

    private $_sDestination = false;
    private $_sExt = false;

    public function load($sLink, $sDir, $sName) {
        $this->_buildDir($sDir);
        $this->_getFileType($sLink);

        $sFileName = md5($sName . PHPFOX_TIME . uniqid());
        $sDest = $this->_sDestination . $sFileName . '.' . $this->_sExt;
        // Load and save file
        file_put_contents($sDest, file_get_contents($sLink));
        // Windows permission problem???
        if (stristr(PHP_OS, "win")) {
            @copy($sDest, $sDest . '.cache');
            @unlink($sDest);
            @copy($sDest . '.cache', $sDest);
            @unlink($sDest . '.cache');
        } else {
            @chmod($sDest, 0644);
        }

        return str_replace('\\', '/', str_replace($sDir, '', $this->_sDestination) . $sFileName .  '%s.' . $this->_sExt);
    }

    private function _getFileType($sLink) {
        $aExts = preg_split("/[\/\\.]/", $sLink);
        $sExt = "";
        if(is_array($aExts) && count($aExts) > 0){
            $iCnt = count($aExts) - 1;
            $sExt = strtolower($aExts[$iCnt]);
        }
        if(!in_array($sExt, array('jpg','gif','png'))){
            $sExt = 'jpg';
        }
        $this->_sExt = $sExt;
    }

    private function _buildDir($sDestination) {
        if (!PHPFOX_SAFE_MODE && Phpfox::getParam('core.build_file_dir')) {
            $aParts = explode('/', Phpfox::getParam('core.build_format'));
            $this->_sDestination = $sDestination;
            foreach ($aParts as $sPart) {
                $sDate = date($sPart) . PHPFOX_DS;
                $this->_sDestination .= $sDate;
                if (!is_dir($this->_sDestination)) {
                    @mkdir($this->_sDestination, 0777);
                    @chmod($this->_sDestination, 0777);
                }
            }

            // Make sure the directory was actually created, if not we use the default dir we know is working
            if (is_dir($this->_sDestination)) {
                return true;
            }
        }

        $this->_sDestination = $sDestination;
    }

}